package com.zengqingfa.imp.demo.service;

import com.alibaba.excel.EasyExcel;
import com.google.common.collect.Lists;
import com.zengqingfa.imp.demo.dao.EmpDao;
import com.zengqingfa.imp.demo.dto.Emp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

/**
 * @fileName: TaskExector
 * @author: zengqf3
 * @date: 2021-3-3 10:11
 * @description:
 */
@Service
@Slf4j
public class TaskExector {

    @Autowired
    private EmpService empService;

    /**
     * 分批次异步导出数据
     *
     * @param map 要导出的批次数据信息
     * @param cdl countDownLatch这个类使一个线程等待其他线程各自执行完毕后再执行。
     */
    @Async("taskExecutor")
    public void executeAsyncTask(Map<String, Object> map, CountDownLatch cdl) {
        long start = System.currentTimeMillis();
        List<Emp> list = Lists.newArrayList();
        try {
            list = empService.findByPage((Integer) map.get("page"), (Integer) map.get("limit"));
        } catch (Exception e) {
            log.error("EmpService#findByPage query error: {}", e);
        }
        String filepath = map.get("path").toString() + map.get("page") + ".xlsx";
        EasyExcel.write(filepath, Emp.class).sheet("模板").doWrite(list);
//        log.info("线程：{},导出excel {}.xlsx   成功,导出数据：{}，耗时 ：{}", Thread.currentThread().getName(), map.get("page"), list.size(), (System.currentTimeMillis() - start));
        list.clear();
        //执行完毕线程数减一
        cdl.countDown();
        log.info("剩余任务数  ===========================>{} ", cdl.getCount());
    }
}
